#include "newframe.h"
#include <QPainterPath>
#include <QPainter>

newFrame::newFrame(QWidget *parent) :
    QFrame(parent)
{

}

newFrame::~newFrame()
{
}

#define TOP_LEFT_CORNER             1 //左上角
#define TOP_RIGHT_CORNER            2 //右上角
#define BOTTOM_RIGHT_CORNER         4 //右下角
#define BOTTOM_LEFT_CORNER          8 //左下角
QPainterPath makeAnyRoundedRect(const QRect& rect,int radius,int corner)
{  //rect 距形
    //参数 radius 圆角距形半径
    //corner 取上面4个值的任意组合。表示那个要圆角。

    QPainterPath path;
    if(corner & TOP_LEFT_CORNER)
    {
        path.moveTo(rect.x() + radius,rect.y());
        path.arcTo(rect.x(),rect.y(),radius*2,radius*2,90.f,90.f);//画左上圆角
    }
    else
    {
        path.moveTo(rect.x(),rect.y());
    }

    if(corner & BOTTOM_LEFT_CORNER)
    {
        path.lineTo(rect.x(),rect.y() + rect.height() -radius);
        path.arcTo(rect.x(),rect.y() + rect.height() - radius *2,radius*2,radius*2,180.0f,90.f);
    }
    else
    {
        path.lineTo(rect.x(),rect.y() + rect.width());
    }

    if(corner & BOTTOM_RIGHT_CORNER)
    {
        path.lineTo(rect.x() + rect.width() - radius,rect.y() + rect.height());
        path.arcTo(rect.x() + rect.width() - 2*radius,rect.y() + rect.height() - 2*radius,radius*2,radius*2,270.0f,90.f);
    }
    else
    {
        path.lineTo(rect.x()+ rect.width(),rect.y() + rect.height());
    }

    if(corner & TOP_RIGHT_CORNER)
    {
        path.lineTo(rect.x() + rect.width(),rect.y() + radius);
        path.arcTo(rect.x() + rect.width() - 2*radius,rect.y(),radius*2,radius*2,0.f,90.f);
    }
    else
    {
        path.lineTo(rect.x()+ rect.width(),rect.y());
    }
    return path;
}

void newFrame::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    QRect rect = this->rect();
    int border_radius = 24;
    auto picPath = makeAnyRoundedRect(rect, border_radius, TOP_LEFT_CORNER | TOP_RIGHT_CORNER | BOTTOM_LEFT_CORNER | BOTTOM_RIGHT_CORNER);
    painter.setClipPath(picPath);
    QPixmap pic;
    pic.load(":/res/bk.png");
    QPixmap scaledPixmap = pic.scaled(rect.size(), Qt::KeepAspectRatio);
    painter.drawPixmap(rect, scaledPixmap);

    QFrame::paintEvent(event);
}

